package mutil.thread;

import org.omg.IOP.IOR;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by luoqifei on 17-5-24.
 */
public class Processor {
    public static void writeThreadInfo(PrintWriter pw , Thread thread , Thread.State status ){
        pw.printf("Id %d - %s \n",thread.getId(),thread.getName());
        pw.printf("Priority : %d \n",thread.getPriority());
        pw.printf("Old status : %s\n",status);
        pw.printf("************************\n");
    }
    public static void main(String args[]){
        Thread threads[] = new Thread[10];
        Thread.State states[] = new Thread.State[10];
        for (int i=0;i<10;i++) {
            threads[i] = new Thread(new Calculator(i));
            if(i%2 == 0) {
                threads[i].setPriority(Thread.MAX_PRIORITY);
            }else {
                threads[i].setPriority(Thread.MIN_PRIORITY);
            }
            threads[i].setName("thread-"+i);
        }
        try {
            FileWriter file = new FileWriter("thread.log");
            PrintWriter printWriter = new PrintWriter(file);
            for (int i=0;i<10;i++) {
                printWriter.println("status of thread-"+i+" : "+threads[i].getState());
                states[i] = threads[i].getState();
            }
            for (int i=0;i<10;i++) {
                threads[i].start();
            }
            boolean finish = false;
            while (finish){
                for (int i=0;i<10;i++) {
                    if(threads[i].getState() != states[i]){
                        writeThreadInfo(printWriter,threads[i],states[i]);
                        states[i] = threads[i].getState();
                    }
                }
                finish = true;
                for (int i=0;i<10;i++) {
                    finish = finish && (threads[i].getState() == Thread.State.TERMINATED);
                }
            }
        }catch (IOException e){

        }


    }
}
